package com.quick.develop.flowable.utils.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.quick.develop.flowable.domain.BaseDO;
import com.quick.develop.framework.security.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * @author junyuan.liu
 * @description 通用参数填充实现类 如果没有显式的对通用参数进行赋值，这里会对通用参数进行填充、赋值
 * @date 2022/5/16 19:19
 */

public class DefaultDBFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseDO) {
            BaseDO baseDO = (BaseDO) metaObject.getOriginalObject();
            Date current = new Date();
            String userId = SecurityUtils.getUserCode();//
            String userName = SecurityUtils.getUsername();
            baseDO.setCreatedDate(current);
            baseDO.setUpdatedDate(current);
            // 当前登录用户不为空 强制更新
            Optional.ofNullable(userId).ifPresent(i -> {
                baseDO.setCreatedUserCode(i);
                baseDO.setUpdatedUserCode(i);
            });
            Optional.ofNullable(userName).ifPresent(e -> {
                baseDO.setCreatedUserName(e);
                baseDO.setUpdatedUserName(e);
            });
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时间为空，则以当前时间为更新时间
        String userId = SecurityUtils.getUserCode();//
        String userName = SecurityUtils.getUsername();
        setFieldValByName("updatedDate", new Date(), metaObject);
        // 当前登录用户不为空，更新人为空，则当前登录用户为更新人
        Optional.ofNullable(userId)
                .ifPresent(e -> setFieldValByName("updatedUserCode", e, metaObject));

        Optional.ofNullable(userName)
                .ifPresent(e -> setFieldValByName("updatedUserName", e, metaObject));

    }
}
